﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.AspNetCore.StaticFiles;
using community.Models;

namespace community.Controllers
{
    [Route("api/export")]
    [ApiController]
    public class ExportController : ControllerBase
    {
        // 示例：导出居民信息
        [HttpPost]
        public IActionResult ExportData([FromBody] ExportRequest exportRequest)
        {
            // 数据模拟（实际情况下会从数据库中查询数据）
            var residents = new List<dynamic>
            {
                new { Id = 1, Name = "张三", Age = 70, Gender = "男", RoomNumber = "101" },
                new { Id = 2, Name = "李四", Age = 65, Gender = "女", RoomNumber = "102" }
            };

            if (exportRequest.DataType == "Residents")
            {
                var csvContent = GenerateCsv(residents);
                var fileName = "Residents_Data.csv";
                return File(Encoding.UTF8.GetBytes(csvContent), "text/csv", fileName);
            }

            // 支持其他类型的数据导出：如房屋信息、物业信息等
            // 添加相关的导出逻辑
            return BadRequest("不支持该数据类型");
        }

        // CSV格式化方法
        private string GenerateCsv<T>(List<T> data)
        {
            var sb = new StringBuilder();
            var properties = typeof(T).GetProperties().Select(p => p.Name).ToArray();
            sb.AppendLine(string.Join(",", properties)); // CSV表头

            foreach (var item in data)
            {
                var values = properties.Select(p => item.GetType().GetProperty(p)?.GetValue(item, null)?.ToString() ?? "").ToArray();
                sb.AppendLine(string.Join(",", values)); // CSV数据
            }

            return sb.ToString();
        }
    }
}
